import { formatRule, mergeMaps } from '@/utils/fomatter';

import Taro from '@tarojs/taro'
import React, { Component } from 'react';
import { NavBar } from "@/components";
import { View, Image, Text } from '@tarojs/components';
import { Toast, Button } from '@antmjs/vantui';
import RiskAssessmentPopup from "./popup/index";
import { getQuestionnaire } from '@/services/api/common';
import { submitRiskAnswer, submitRiskAssessment } from '@/services/api/eligible_investors';
import { stringifyUrl } from 'query-string';
import { connect } from 'react-redux';


import './index.scss'




// interface RiskAssessmentProps {}
// <RiskAssessmentProps, any>

// interface RiskAssessmentState {
//     showPopUP: boolean,
//     data : Array<any>,
//     index: number,
// }

class RiskAssessment extends Component<any, any> {

  constructor(props) {
    super(props);
  }

  //
  state = {
    showPopUP: false,
    model: {},
    data: [],
    index: 0,
    riskAssessmentDisabled: true
  }

  // 建议在页面初始化时把 getCurrentInstance() 的结果保存下来供后面使用，
  // 而不是频繁地调用此 API
  $instance = Taro.getCurrentInstance()

  componentWillMount() {
    const preloadData = this.$instance.preloadData
    var params = this.$instance.router?.params

    if (preloadData != null && Object.keys(preloadData).length > 0) {
      this.setState({ data: preloadData['data'], index: preloadData['index'] })
    } else {
      getQuestionnaire(1).then((resp) => {
        if (resp.code === 200) {
          this.setState({ model: resp.data, data: resp.data['questions'], index: 0 })
        }
      })
    }
    Taro.preload({})  // 清空
  }

  clickOption(optionIndex) {
    const { data, index } = this.state;
    if (data && data.length > 0) {
      const itemData: Map<String, any> = data[index];
      var options = Array.from(itemData['options']);
      //
      itemData['selectOptions'] = options[optionIndex];
      this.clickNextQuestion();
    }
    this.setState({ data: data })
  }

  clickPreviousQuestion() {
    const { data, index } = this.state;
    this.setState({ index: index - 1 })

  }


  clickNextQuestion() {
    const { data, index } = this.state;
    console.log(index)
    console.log(data.length - 1)
    if (index === data.length - 1) {
      var allanswer = true;
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        if (element['selectOptions'] == null) {
          allanswer = false
          Toast.fail(`请选择${index + 1}的答案`);
          break;
        }
      }
      this.setState({ riskAssessmentDisabled: !allanswer })

      if (allanswer) {
        Toast.show('您已答完所有的题目，可以提交评测了哟');
      }
      return
    }


    this.setState({ index: index + 1 })
    if (index + 1 === data.length - 1) {
      var allanswer = true;
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        if (element['selectOptions'] == null) {
          allanswer = false
          break;
        }
      }
      this.setState({ riskAssessmentDisabled: !allanswer })

    }

    // Taro.preload({ 'data': data, 'index': index + 1 })
    /// 小程序的页面栈有限制 所以不跳转了
    // Taro.navigateTo({
    //     url: '/eligible_investors/risk_assessment/index'
    // });
  }



  submitRiskAssessment() {
    this.setState({ showPopUP: true });
  }

  onClose() {
    this.setState({ showPopUP: false });
  }


  onSubmit() {
    const { model, data } = this.state;
    console.log(model);

    var answerValueStr = ''
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      if (element['selectOptions'] != null) {
        answerValueStr = answerValueStr + element['selectOptions']['questionId'] + ',' + element['selectOptions']['optValue'] + ';'
      }
    }
    // 获取传递的 map 对象
    var params: any = this.$instance.router?.params
    // 标记是新的提交
    if ('isOldRisk' in params) {
      params.isOldRisk = false
    }
    if (params != null) {
      if (params['riskAccept'] <= 0) {

        submitRiskAssessment(model['questionnaireId'], answerValueStr).then((resp) => {
          if (resp.code === 200) {
            this.props.dispatch({
              type: 'certified/asyncGetUserDetail',
            })
            Taro.redirectTo({
              url: '/eligible_investors/risk_assessment/detail/index'
            })
          }
        })
      } else {
        submitRiskAnswer(model['questionnaireId'], answerValueStr).then((resp) => {
          if (resp.code === 200) {
            this.props.dispatch({
              type: 'certified/asyncGetUserDetail',
            })
            const c = Object.assign(params, resp.data);
            const d = Object.assign(c, { 'showSubmit': '1' });
            Taro.preload(d)

            Taro.redirectTo({
              url: stringifyUrl({ url: '/eligible_investors/risk_assessment/detail/index', query: resp.data }, { encode: false })
            });
          }
        })
      }
    }
  }

  render() {
    const { statusBarHeight } = Taro.getSystemInfoSync()
    const { showPopUP, data, index, riskAssessmentDisabled } = this.state;

    var options = []
    var selectOptions = {}
    var itemData = {}
    if (data && data.length > 0) {
      itemData = data[index]
      //
      options = Array.from(itemData['options']);
      //
      selectOptions = itemData['selectOptions'];
    }
    console.log(riskAssessmentDisabled);

    return (
      <View className='page'>
        <NavBar name=''></NavBar>
        <View className='desc'>
          <Image className='bg-image' src=''></Image>
          <View className='desc-text' style={{ paddingTop: statusBarHeight + 44 + 8 }}>
            <Text>风险评测</Text>
            <Text>{formatRule('风险提示：')}</Text>
            <Text>{formatRule('基金投资需承担各类风险，本金可能遭受损失。')}</Text>
            <Text>{formatRule('同时，还要考虑市场风险、信用风险、流动风险、操作风险等各类投资风险。')}</Text>
            <Text>{formatRule('您在基金认购过程中应当注意核对自己的风险识别和风险承受能力，选择与自己风险识别能力和风险承受能力相匹配的私募基金。')}</Text>

          </View>
        </View>
        <View className='question'>
          <View className='name'>
            <Text>{`${index + 1} /  ${itemData['questionContent']}`}</Text>
          </View>
          <View className='option'>
            {
              options.map((item: Map<string, any>, index) => (

                <View className={`option-item ${item && selectOptions && Object.keys(selectOptions).length > 0 && item['optValue'] === selectOptions['optValue'] ? 'option-item-select' : ''}`} onClick={() => {
                  this.clickOption(index)
                }}
                >{`${item['optValue']}. ${item['optContent']}`}</View>
              ))
            }
          </View>
          <View className='bottom-button'>
            {
              index > 0 ? <Button className='left-button' onClick={this.clickPreviousQuestion.bind(this)}>上一题</Button> : null
            }

            {
              index < data.length - 1 ? <Button className='right-button-next' onClick={this.clickNextQuestion.bind(this)}>下一题</Button> : null
            }

            {
              index === data.length - 1 ? <Button className='right-button' disabled={riskAssessmentDisabled} onClick={this.submitRiskAssessment.bind(this)}>提交测评</Button> : null
            }
          </View>

        </View>
        <RiskAssessmentPopup showPopUP={showPopUP} onSubmit={this.onSubmit.bind(this)} onClose={this.onClose.bind(this)}></RiskAssessmentPopup>
        <Toast />
      </View>
    );
  }
}
const mapStateToProps = (state) => {
  return {
    certified: state.certified, //这里的example表示后面用this.props.example获取state（根节点）中exmpale命名空间（model的example.js中的state所有数据）的数据
  }
}
export default connect(mapStateToProps)(RiskAssessment);
